package com.ronghui.cash.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ronghui.cash.entity.*;
import com.ronghui.cash.parambean.AuthBasicInfoBean;
import com.ronghui.cash.parambean.AuthContactBean;
import com.ronghui.cash.parambean.AuthIdentityBean;
import com.ronghui.cash.parambean.BankCardNoBean;
import com.ronghui.cash.service.*;
import com.ronghui.cash.util.*;
import com.ronghui.cash.util.lianlian.bean.BankCardBean;
import com.ronghui.cash.util.lianlian.bean.SignApplyBean;
import com.ronghui.cash.util.lianlian.pay.LianLianPayConfig;
import com.ronghui.cash.util.lianlian.util.YTHttpHandler;
import com.ronghui.cash.vo.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 认证相关的控制器
 *
 */

@RestController
@RequestMapping("auth")
public class AuthController extends BaseController{

    @Value("${baseUrl}")
    private String baseUrl;

    @Value("${headImgUrl}")
    private String headImgUrl;

    @Value("${identityImgUrl}")
    private String identityImgUrl;

    @Value("${identityImgTempUrl}")
    private String identityImgTempUrl;

    @Autowired
    UserService userService;

    @Autowired
    AuthRejectService authRejectService;

    @Autowired
    AuthIdentityService authIdentityService;

    @Autowired
    AuthService authService;

    @RequestMapping(method = RequestMethod.POST, value = "identity")
    public Response tongdunIdentity(@Validated AuthIdentityBean aib) throws Exception {
        Long userId = super.getUserId();
        String identity = aib.getIdentity().toUpperCase();

        //只允许佛山的身份证
        if("4406".equals(identity.substring(0,4))){
            return failure("目前仅允许佛山市的身份证进行认证");
        }

        IdcardValidator iv = new IdcardValidator();
        if (!iv.isValidatedAllIdcard(aib.getIdentity())) {
            super.logger.info("userId:" + userId + ", 身份证格式错误:" + identity);
            return failure("身份证格式错误");
        }

        int age = CardUtil.getCardAgeInfo(identity);
        if (age < 19 || age > 51) {
            super.logger.info("userId:" + userId + ", 认证失败,年龄不符合,正常流程是20-50，该用户年龄是:" + age);
            return failure("认证失败,您的年龄不符合我们的授信标准，无法进行下一步授权。如有疑问，请联系客服：400-0072-102");
        }

        AuthIdentity authIdentity = authIdentityService.selectOne(new EntityWrapper<AuthIdentity>().eq("identity",identity));
        if(authIdentity != null){
            super.logger.info("userId:" + userId + ", 认证失败，该身份证已经进行过绑定");
            return failure("认证失败，该身份证已经进行过绑定");
        }

        // 如果申请过认证直接返回错误
        AuthProject apBaiqishi = authService.getAuthProject(userId, ConstUtil.BAIQISHI);
        if (apBaiqishi != null) {
            super.logger.info("userId:" + userId + ", 您已经进行过身份认证了");
            return failure("您已经进行过身份认证了");
        }

        String idenFrontPicKey = "token:" + request.getParameter("token") + "frontIdenPic";
        String idenReversePicKey = "token:" + request.getParameter("token") + "reverseIdenPic";
        String idenHandHoldingPicKey = "token:" + request.getParameter("token") + "handHoldingIdenPic";

        String frontIdenPic = (String)super.redisTemplate.opsForValue().get(idenFrontPicKey);
        String reverseIdenPic = (String)super.redisTemplate.opsForValue().get(idenReversePicKey);
        String handHoldingIdenPic = (String)super.redisTemplate.opsForValue().get(idenHandHoldingPicKey);
        if(StringUtil.isEmpty(frontIdenPic) || StringUtil.isEmpty(reverseIdenPic) || StringUtil.isEmpty(handHoldingIdenPic)){
            return failure("请先上传身份证照片");
        }

        String name = aib.getName();
        User user = userService.selectById(userId);
        String mobile = user.getUsername();

        String datetime = DateUtil.getCurrentDateTime();

        AuthReject authReject = authRejectService.selectOne(new EntityWrapper<AuthReject>()
                .eq("user_id",userId)
                .eq("status",1)
                .gt("unlock_time", DateUtil.getCurrentDate())

        );
        if(authReject != null){
            super.logger.info("userId:" + userId + ", 用户已被锁，不允许进行身份认证，解锁时间：" + authReject.getUnlockTime());
            return failure("您暂时不符合我们的授信标准，无法进行下一步授权。如有疑问，请联系客服：400-0072-102");
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("partnerId", "didafenqi");
        map.put("verifyKey", "5921d56af38a47dfa487b3f0033321b1");
        map.put("appId", "test");
        map.put("eventType", "loan");
        map.put("certNo", identity);
        map.put("name", name);
        map.put("mobile", mobile);

        super.logger.debug("userId:" + userId + ", 请求白骑士的参数：" + JSONObject.toJSONString(map));
        String result = HttpPostUtil.HttpPostWithJson("https://api.baiqishi.com/services/decision",map);
        JSONObject jsonResult = null;
        try {
            jsonResult = JSONObject.parseObject(result);
            if (!"BQS000".equals(jsonResult.getString("resultCode"))) {
                super.logger.error("userId:" + userId + ",白骑士请求错误，错误代码：" + jsonResult.getString("resultCode"));
                return failure("申请身份验证失败,请稍后再试");
            }
        } catch (Exception e) {
            super.logger.error("userId:" + userId + ",白骑士的返回值错误，result:" + result);
            return failure("申请身份验证失败,请稍后再试");
        }

        //获取风险检查项
        JSONArray jsonArr = null;
        super.logger.debug("=========================  白骑士风险检查项结果 start   =============================");
        try {
            jsonArr = jsonResult.getJSONArray("strategySet");
            super.logger.debug(jsonArr.toJSONString());
        }catch (JSONException e){
            super.logger.debug(result);
        }

        super.logger.debug("=========================  白骑士风险检查项结果 end   =============================");

        //TODO 做风险处理
        /*if (response.getFinal_score() > 50) {

            String remark = "同盾认证失败，分数过低，分数为：" + response.getFinal_score();
            logger.info("=========:" + remark);
            AuthReject ar = new AuthReject();
            ar.setId(super.getNextId());
            ar.setCreateTime(datetime);
            ar.setRemark(remark);
            ar.setStatus(1);
            ar.setType(ConstUtil.BAIQISHI);
            ar.setUnlockTime(DateUtil.getCaleDateString(90));// 解锁时间

            ar.setUserId(userId);
            authRejectService.insert(ar);

            return failure("您暂时不符合我们的授信标准，无法进行下一步授权。如有疑问，请联系客服电话：400-0072-102");
        }*/


        String remark = "";

        AuthBaiqishi ab = new AuthBaiqishi();
        ab.setId(super.getNextId());
        ab.setCreateTime(datetime);
        ab.setFinalDecision(jsonResult.getString("finalDecision"));
        ab.setStrategySet(jsonResult.getJSONArray("").toJSONString());
        ab.setStatus(1);
        if(jsonArr != null){
            ab.setStrategySet(jsonArr.toJSONString());
        }else{
            ab.setStrategySet("[]");
        }
        if(jsonResult.getString("finalScore") != null){
            ab.setFinalScore(Integer.parseInt(jsonResult.getString("finalScore")));
        }else{
            ab.setFinalScore(0);
        }
        ab.setStatus(1);
        ab.setUserId(userId);

        apBaiqishi = new AuthProject();
        apBaiqishi.setId(super.getNextId());
        apBaiqishi.setStatus(1);
        apBaiqishi.setType(ConstUtil.BAIQISHI);
        apBaiqishi.setCreateTime(datetime);
        apBaiqishi.setUserId(userId);

        /*try {
            File saveFrontIdenPic = new File(identityImgTempUrl + frontIdenPic);
            saveFrontIdenPic.renameTo(new File(identityImgUrl + frontIdenPic));
        }catch (Exception e){
            logger.error("userId:{}, 保存身份证照（人像面）失败",userId);
            throw new Exception();
        }
        try {
            File saveReverseIdenPic = new File(identityImgTempUrl + reverseIdenPic);
            saveReverseIdenPic.renameTo(new File(identityImgUrl + reverseIdenPic));
        }catch (Exception e){
            logger.error("userId:{}, 保存身份证照（国徽面）失败",userId);
            throw new Exception();
        }

        try {
            File saveHandHoldingIdenPic = new File(identityImgTempUrl + handHoldingIdenPic);
            saveHandHoldingIdenPic.renameTo(new File(identityImgUrl + handHoldingIdenPic));
        }catch (Exception e){
            logger.error("userId:{}, 保存手持身份证照失败",userId);
            throw new Exception();
        }*/
        boolean saveFrontIdenPic = FileUtil.copyFile(identityImgTempUrl + frontIdenPic,identityImgUrl + frontIdenPic);
        boolean saveReverseIdenPic = FileUtil.copyFile(identityImgTempUrl + reverseIdenPic,identityImgUrl + reverseIdenPic);
        boolean saveHandHoldingIdenPic = FileUtil.copyFile(identityImgTempUrl + handHoldingIdenPic,identityImgUrl + handHoldingIdenPic);
        if(!saveFrontIdenPic){
            logger.error("userId:{},保存身份证照（人像面）失败",userId);
            return failure("保存身份证照（人像面）失败");
        }

        if(!saveReverseIdenPic){
            logger.error("userId:{},保存身份证照（国徽面）失败",userId);
            return failure("保存身份证照（国徽面）失败");
        }

        if(!saveHandHoldingIdenPic){
            logger.error("userId:{},保存手持身份证照失败",userId);
            return failure("保存手持身份证照失败");
        }

        AuthIdentity ai = new AuthIdentity();
        ai.setCreateTime(datetime);
        ai.setId(super.getNextId());
        ai.setIdentity(identity);
        ai.setName(name);
        ai.setPhone(mobile);
        ai.setStatus(1);
        ai.setUserId(userId);
        ai.setFrontPic(frontIdenPic);
        ai.setReversePic(reverseIdenPic);
        ai.setHandHoldingPic(handHoldingIdenPic);

        authService.saveIdentity(apBaiqishi, ai, ab);
        return success();
    }


    /**
     * 认证不通过时保存到auth_reject
     * @param remark
     * @param userId
     * @return
     */
    public Response notPassTongdun(String remark,Long userId,String datetime,String phone,String name,String identity){
        super.logger.debug(remark);

        AuthReject ar = new AuthReject();
        ar.setId(super.getNextId());
        ar.setCreateTime(datetime);
        ar.setRemark(remark);
        ar.setStatus(1);
        ar.setType(ConstUtil.BAIQISHI);
        ar.setUnlockTime(DateUtil.getCaleDateString(90));// 解锁时间90天后

        ar.setUserId(userId);
        authRejectService.insert(ar);
        super.logger.info("userId:" + userId + ", " + remark);

        return failure("您暂时不符合我们的授信标准，无法进行下一步授权。如有疑问，请联系客服：400-0072-102");
    }

    /**
     * 上传身份证照（人像面）
     * @param idenFrontPic
     * @return idenPicStr
     */
    @RequestMapping(method = RequestMethod.POST, value = "uploadIdenFrontPic")
    public Response uploadIdenFrontPic(MultipartFile idenFrontPic){
        if(idenFrontPic == null){
            return failure("请先上传身份证照（人像面）");
        }

        String idenPicStr = null;
        try {
            idenPicStr = FileUtil.saveFile(idenFrontPic,identityImgTempUrl,"");
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(idenPicStr == null){
            return failure("上传身份证照（人像面）失败");
        }
        String idenFrontPicKey = "token:" + request.getParameter("token") + "frontIdenPic";
        super.redisTemplate.opsForValue().set(idenFrontPicKey,idenPicStr,1800, TimeUnit.SECONDS);

        return success();
    }

    /**
     * 上传身份证照(国徽面)
     * @param idenReversePic
     * @return idenPicStr
     */
    @RequestMapping(method = RequestMethod.POST, value = "uploadIdenReversePic")
    public Response uploadIdenReversePic(MultipartFile idenReversePic){
        if(idenReversePic == null){
            return failure("请先上传身份证照(国徽面)");
        }

        String idenPicStr = null;
        try {
            idenPicStr = FileUtil.saveFile(idenReversePic,identityImgTempUrl,"");
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(idenPicStr == null){
            return failure("上传身份证照(国徽面)失败");
        }
        String idenReversePicKey = "token:" + request.getParameter("token") + "reverseIdenPic";
        super.redisTemplate.opsForValue().set(idenReversePicKey,idenPicStr,1800,TimeUnit.SECONDS);

        return success();
    }

    /**
     * 上传手持身份证照
     * @param idenHandHoldingPic
     * @return idenPicStr
     */
    @RequestMapping(method = RequestMethod.POST, value = "uploadIdenHandHoldingPic")
    public Response uploadIdenHandHoldingPic(MultipartFile idenHandHoldingPic){
        if(idenHandHoldingPic == null){
            return failure("请先上传手持身份证照");
        }

        String idenPicStr = null;
        try {
            idenPicStr = FileUtil.saveFile(idenHandHoldingPic,identityImgTempUrl,"");
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(idenPicStr == null){
            return failure("上传手持身份证照失败");
        }
        String idenHandHoldingPicKey = "token:" + request.getParameter("token") + "handHoldingIdenPic";
        super.redisTemplate.opsForValue().set(idenHandHoldingPicKey,idenPicStr,1800,TimeUnit.SECONDS);

        return success();
    }

    /**
     * 重新上传身份证照片
     */
    @RequestMapping(method = RequestMethod.POST, value = "auth/modifyIdentityPic")
    public Response modifyIdentityPic() throws Exception {

        Long userId = getUserId();
        AuthIdentity authIdentity = authIdentityService.selectOne(new EntityWrapper<AuthIdentity>().eq("user_id",userId));

        if(authIdentity.getAuditStatus() == 0){
            return failure("该身份证资料已上传");
        }

        String idenFrontPicKey = "token:" + request.getParameter("token") + "frontIdenPic";
        String idenReversePicKey = "token:" + request.getParameter("token") + "reverseIdenPic";
        String handHoldingPicKey = "token:" + request.getParameter("token") + "handHoldingIdenPic";

        String frontIdenPic = (String) super.redisTemplate.opsForValue().get(idenFrontPicKey);
        String reverseIdenPic = (String) super.redisTemplate.opsForValue().get(idenReversePicKey);
        String handHoldingIdenPic = (String) super.redisTemplate.opsForValue().get(handHoldingPicKey);
        if(StringUtil.isEmpty(frontIdenPic) || StringUtil.isEmpty(reverseIdenPic) || StringUtil.isEmpty(handHoldingIdenPic)){
            return failure("请先上传身份证照片");
        }

		/*try {
            File saveFrontIdenPic = new File(identityImgTempUrl + frontIdenPic);
            saveFrontIdenPic.renameTo(new File(identityImgUrl + frontIdenPic));
        }catch (Exception e){
            logger.error("userId:{}, 保存身份证照（人像面）失败",userId);
            throw new Exception();
        }
        try {
            File saveReverseIdenPic = new File(identityImgTempUrl + reverseIdenPic);
            saveReverseIdenPic.renameTo(new File(identityImgUrl + reverseIdenPic));
        }catch (Exception e){
            logger.error("userId:{}, 保存身份证照（国徽面）失败",userId);
            throw new Exception();
        }

        try {
            File saveHandHoldingIdenPic = new File(identityImgTempUrl + handHoldingIdenPic);
            saveHandHoldingIdenPic.renameTo(new File(identityImgUrl + handHoldingIdenPic));
        }catch (Exception e){
            logger.error("userId:{}, 保存手持身份证照失败",userId);
            throw new Exception();
        }*/
        boolean saveFrontIdenPic = FileUtil.copyFile(identityImgTempUrl + frontIdenPic,identityImgUrl + frontIdenPic);
        boolean saveReverseIdenPic = FileUtil.copyFile(identityImgTempUrl + reverseIdenPic,identityImgUrl + reverseIdenPic);
        boolean saveHandHoldingIdenPic = FileUtil.copyFile(identityImgTempUrl + handHoldingIdenPic,identityImgUrl + handHoldingIdenPic);
        if(!saveFrontIdenPic){
            logger.error("userId:{},保存身份证照（人像面）失败",userId);
            return failure("保存身份证照（人像面）失败");
        }

        if(!saveReverseIdenPic){
            logger.error("userId:{},保存身份证照（国徽面）失败",userId);
            return failure("保存身份证照（国徽面）失败");
        }

        if(!saveHandHoldingIdenPic){
            logger.error("userId:{},保存手持身份证照失败",userId);
            return failure("保存手持身份证照失败");
        }

        FileUtil.deleteFile(identityImgUrl + authIdentity.getFrontPic());
        FileUtil.deleteFile(identityImgUrl + authIdentity.getReversePic());
        FileUtil.deleteFile(identityImgUrl + authIdentity.getHandHoldingPic());

        //更新表记录
        authIdentity.setFrontPic(frontIdenPic);
        authIdentity.setReversePic(reverseIdenPic);
        authIdentity.setHandHoldingPic(handHoldingIdenPic);
        authIdentity.setAuditStatus(0);
        authIdentityService.updateById(authIdentity);
        return success();
    }

    /**
     * 基本信息认证
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "authBasics")
    public Response authBasics(@Validated AuthBasicInfoBean abb) {
        Long userId = super.getUserId();

        AuthProject apBaiqishi = authService.getAuthProject(userId, ConstUtil.BAIQISHI);
        if (apBaiqishi == null || apBaiqishi.getStatus() != 1){
            return failure("您的身份认证未通过");
        }

        AuthProject apBasicInfo= authService.getAuthProject(userId, ConstUtil.BASICINFO);
        if (apBasicInfo != null && apBasicInfo.getStatus() == 1){
            return failure("您已经进行过基本信息认证了");
        }

        String datetime = DateUtil.getCurrentDateTime();

        AuthBasicInfo abi = new AuthBasicInfo();
        abi.setId(super.getNextId());
        abi.setNowProvince(abb.getNowProvince());
        abi.setNowTown(abb.getNowTown());
        abi.setNowArea(abb.getNowArea());
        abi.setNowAddress(abb.getNowAddress());
        abi.setNowProvinceCode(abb.getNowProvinceCode());
        abi.setNowTownCode(abb.getNowTownCode());
        abi.setNowAreaCode(abb.getNowAreaCode());
        abi.setLiveTime(abb.getLiveTime());
        abi.setIndustry(abb.getIndustry());
        abi.setWorkPlace(abb.getWorkPlace());
        abi.setUnitName(abb.getUnitName());
        abi.setUnitPhone(abb.getUnitPhone());
        abi.setUnitProvince(abb.getUnitProvince());
        abi.setUnitTown(abb.getUnitTown());
        abi.setUnitArea(abb.getUnitArea());
        abi.setUnitAddress(abb.getUnitAddress());
        abi.setUnitProvinceCode(abb.getUnitProvinceCode());
        abi.setUnitTownCode(abb.getUnitTownCode());
        abi.setUnitAreaCode(abb.getUnitAreaCode());

        abi.setUserId(userId);
        abi.setCreateTime(DateUtil.getCurrentDateTime());
        abi.setStatus(1);

        AuthProject ap = new AuthProject();
        ap.setId(super.getNextId());
        ap.setStatus(1);
        ap.setType(ConstUtil.BASICINFO);
        ap.setCreateTime(datetime);
        ap.setUserId(userId);

        authService.authBasicInfo(ap, abi);
        return success();
    }

    /**
     * 联系人认证
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "authContact")
    public Response contactIdentity(@Validated AuthContactBean acb) {
        Long userId = super.getUserId();

        AuthProject apBaiqishi = authService.getAuthProject(userId, ConstUtil.BAIQISHI);
        if (apBaiqishi == null || apBaiqishi.getStatus() != 1){
            return failure("您的身份认证未通过");
        }

        AuthProject apBasicInfo = authService.getAuthProject(userId, ConstUtil.BASICINFO);
        if (apBasicInfo == null || apBasicInfo.getStatus() != 1){
            return failure("您的基本资料认证未通过");
        }

        AuthProject apContact = authService.getAuthProject(userId, ConstUtil.CONTACT);
        if (apContact != null && apContact.getStatus() == 1){
            return failure("您已经进行过人际关系认证了");
        }

        String datetime = DateUtil.getCurrentDateTime();

        AuthContact authContact1 = new AuthContact();
        authContact1.setCreateTime(datetime);
        authContact1.setId(super.getNextId());
        authContact1.setName(acb.getName1());
        authContact1.setPhone(acb.getPhone1());
        authContact1.setStatus(1);
        authContact1.setType(Integer.parseInt(acb.getType1()));
        authContact1.setLevel(Integer.parseInt(acb.getLevel1()));
        authContact1.setUserId(userId);

        AuthContact authContact2 = new AuthContact();
        authContact2.setCreateTime(datetime);
        authContact2.setId(super.getNextId());
        authContact2.setName(acb.getName2());
        authContact2.setPhone(acb.getPhone2());
        authContact2.setStatus(1);
        authContact2.setType(Integer.parseInt(acb.getType2()));
        authContact2.setLevel(Integer.parseInt(acb.getLevel2()));
        authContact2.setUserId(userId);

        AuthContact authContact3 = new AuthContact();
        authContact3.setCreateTime(datetime);
        authContact3.setId(super.getNextId());
        authContact3.setName(acb.getName3());
        authContact3.setPhone(acb.getPhone3());
        authContact3.setStatus(1);
        authContact3.setType(Integer.parseInt(acb.getType3()));
        authContact3.setLevel(Integer.parseInt(acb.getLevel3()));
        authContact3.setUserId(userId);

        AuthContact authContact4 = new AuthContact();
        authContact4.setCreateTime(datetime);
        authContact4.setId(super.getNextId());
        authContact4.setName(acb.getName4());
        authContact4.setPhone(acb.getPhone4());
        authContact4.setStatus(1);
        authContact4.setType(Integer.parseInt(acb.getType4()));
        authContact4.setLevel(Integer.parseInt(acb.getLevel4()));
        authContact4.setUserId(userId);

        AuthContact authContact5 = new AuthContact();
        authContact5.setCreateTime(datetime);
        authContact5.setId(super.getNextId());
        authContact5.setName(acb.getName5());
        authContact5.setPhone(acb.getPhone5());
        authContact5.setStatus(1);
        authContact5.setType(Integer.parseInt(acb.getType5()));
        authContact5.setLevel(Integer.parseInt(acb.getLevel5()));
        authContact5.setUserId(userId);

        List<AuthContact> listAuthContact = new ArrayList<AuthContact>();
        listAuthContact.add(authContact1);
        listAuthContact.add(authContact2);
        listAuthContact.add(authContact3);
        listAuthContact.add(authContact4);
        listAuthContact.add(authContact5);

        AuthProject ap = new AuthProject();
        ap.setId(super.getNextId());
        ap.setStatus(1);
        ap.setType(ConstUtil.CONTACT);
        ap.setCreateTime(datetime);
        ap.setUserId(userId);

        authService.authContact(ap, listAuthContact);
        return success();
    }

    /**
     * 手机应用SDK 连连支付 4.2 签约
     *
     * @param bankCardNoBean
     * @return
     */
    @RequestMapping("appSignApply")
    public Response lianlianAppSignApply(@Validated BankCardNoBean bankCardNoBean) {
        Long userId = super.getUserId();

        AuthProject apBaiqishi = authService.getAuthProject(userId, ConstUtil.BAIQISHI);
        if (apBaiqishi == null || apBaiqishi.getStatus() != 1){
            return failure("您的身份认证未通过");
        }

        AuthProject apBasicInfo = authService.getAuthProject(userId, ConstUtil.BASICINFO);
        if (apBasicInfo == null || apBasicInfo.getStatus() != 1){
            return failure("您的基本资料认证未通过");
        }

        AuthProject apContact = authService.getAuthProject(userId, ConstUtil.CONTACT);
        if (apContact == null || apContact.getStatus() != 1){
            return failure("您的人际关系认证未通过");
        }

        AuthProject apBank = authService.getAuthProject(userId, ConstUtil.BANK);
        if (apBank != null && apBank.getStatus() == 1){
            return failure("您已经绑定过银行卡了");
        }

        AuthIdentity ai = authService.getIdentity(userId);

        String bankCard = bankCardNoBean.getBankCardNo();
        SignApplyBean sab = new SignApplyBean();
        sab.setOid_partner(LianLianPayConfig.OID_PARTNER);
        sab.setSign_type("RSA");
        sab.setUser_id(userId.toString());
        sab.setId_no(ai.getIdentity());
        sab.setAcct_name(ai.getName());
        sab.setCard_no(bankCard);
        sab.setSign(LianLianPayConfig.getSign(sab));
        String reqJson = JSON.toJSONString(sab);
        super.logger.info("====== userId:" + userId +", 手机应用SDK 连连支付 4.2 签约请求参数   ========: " + reqJson);

        // 在redis里面缓存一条银行卡数据
        super.redisTemplate.opsForValue().set("tempBankCard:" + userId, bankCard,60 * 60 * 24, TimeUnit.SECONDS);// 24小时内有效

        return success(sab);
    }


    /**
     * 绑定银行卡 因为连连在这个接口上没有notify,所以只能用查询的方式来进行绑定银行卡。 连连支付 4.8. 用户签约信息查询 API 接口
     *
     * @return
     */
    @RequestMapping("checkBankcard")
    public Response lianlianBankcardbindlist() {
        Long userId = getUserId();
        // 已经绑定过银行卡时，直接返回
        AuthProject apBank = authService.getAuthProject(userId, ConstUtil.BANK);
        if (apBank != null && apBank.getStatus() == 1){
            return failure("您已经绑定过银行卡了");
        }
        BankCardBean bc = new BankCardBean();
        bc.setUser_id(userId.toString());
        bc.setOffset("0");
        bc.setOid_partner(LianLianPayConfig.OID_PARTNER);
        bc.setSign_type("RSA");
        bc.setPay_type("D");
        bc.setSign(LianLianPayConfig.getSign(bc));
        String reqJson = JSON.toJSONString(bc);
        super.logger.info("==========userId:" + userId + ",  lianlianBankcardbindlist 请求报文为:  ===========: " + reqJson);
        String resJson = YTHttpHandler.getInstance().doRequestPostString(reqJson, "https://queryapi.lianlianpay.com/bankcardbindlist.htm");
        super.logger.info("==========userId:" + userId + ",  lianlianBankcardbindlist 结果报文为:  ===========: " + resJson);

        if ("error".equals(resJson)){
            super.logger.info("==========userId:" + userId + ",  银行卡签约失败");
            return failure("银行卡签约失败");
        }

        JSONObject j = JSON.parseObject(resJson);

        // 没有结果时，直接返回 ret_msg
        if (j.getString("ret_code").equals("8901")) {
            return failure(j.getString("ret_msg"));
        }

        if (!j.getString("ret_code").equals("0000") || !j.getString("count").equals("1")) {
            super.logger.info("==========userId:" + userId + ",  银行卡签约失败");
            return failure("银行卡签约失败");
        }

        String tempBankCard = (String)super.redisTemplate.opsForValue().get("tempBankCard:" + userId);// 取缓存在redis上的记录
        if (tempBankCard == null) {
            super.logger.info("==========userId:" + userId + ",  银行卡签约失败");
            return failure("银行卡签约失败");
        }

        JSONArray ja = j.getJSONArray("agreement_list");
        JSONObject bankJson = ja.getJSONObject(0);// 取第一个数据

        AuthBank ab = new AuthBank();
        ab.setAgreeNo(bankJson.getString("no_agree"));
        ab.setCode(bankJson.getString("bank_code"));
        ab.setCreateTime(DateUtil.getCurrentDateTime());
        ab.setId(super.getNextId());
        ab.setName(bankJson.getString("bank_name"));
        ab.setNumber(tempBankCard);
        ab.setUserId(userId);

        apBank = new AuthProject();
        apBank.setId(super.getNextId());
        apBank.setStatus(1);
        apBank.setType(ConstUtil.BANK);
        apBank.setCreateTime(DateUtil.getCurrentDateTime());
        apBank.setUserId(userId);

        super.logger.info("==========userId:" + userId + ",  银行卡绑定成功");
        authService.authBank(ab, apBank);

        return success();
    }
}
